#include <iostream>
#include <cstring>
#include <functional>
#include <strings.h>
#include <unistd.h>
#include <sys/wait.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
#include "LOG.hpp"
namespace socket_ns
{
    class Socket;
    const static int gbacklog = 8;
    using socket_ptr = std::shared_ptr<Socket>; // 智能指针
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        USAGE_ERROR,
        LISTEN_ERROR
    };
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InetAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual socket_ptr Accepter(InetAddr *addr) = 0; // accept接受的也是一个socket对象
        virtual bool Connector(InetAddr &addr) = 0;
        virtual int SockFd() = 0;

        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }
        bool BulidClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            return Connector(addr);
        }
    };
    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = -1) : _sockfd(sockfd)
        {
        }
        void CreateSocketOrDie() override
        {
            // 创建套接字
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0) // 创建失败
            {
                LOG(FATAL, "socket error\n");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "socket create success,sockfd is: %d\n", _sockfd);
        }
        // bind需要自己的网络地址
        void BindSocketOrDie(InetAddr &addr) override
        {

            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;          // 网络通讯方式为ipv4
            local.sin_port = htons(addr.Port()); // 主机序列转网络序列
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());
            // 0.0.0.0,绑定所有网络接口，无论client通过哪个ip进来都可以访问
            // bind
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }

            LOG(DEBUG, "bind success,sockfd is: %d\n", _sockfd);
        }
        void ListenSocketOrDie() override
        {
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                // 监听失败报错退出
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen success,sockfd is : %d\n", _sockfd);
        }
        // 为什么要返回一个新的套接字呢？未来增加接口(如:recv、send可以直接->调用)
        socket_ptr Accepter(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return nullptr;
            }
            *addr = peer;
            socket_ptr sock = std::make_shared<TcpSocket>(sockfd);
            return sock;
        }
        virtual bool Connector(InetAddr &addr) override
        {
            struct sockaddr_in server;
            // 构建目标主机的socket信息
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect error" << std::endl;
                return false;
            }
            return true;
        }
        int Recv(std::string *out) override
        {
            char inbuffer[1024];
            ssize_t n = recv(_sockfd, inbuffer, sizeof(inbuffer) - 1,0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }
        int Send(const std::string &in) override
        {
            int n = send(_sockfd,in.c_str(),in.size(),0);
            return n;
        }
        int SockFd() override
        {
            return _sockfd;
        }

    private:
        int _sockfd;
    };
}